import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:hbtrans_flutter/beans/busssch_bean.dart';
import 'package:hbtrans_flutter/utils/mydio.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../routes.dart';

class ComPage extends StatefulWidget {
  final status;
  final level;
  final organizId;
  final sonOrganizId;

  const ComPage(
      {Key key, this.status, this.level, this.organizId, this.sonOrganizId})
      : super(key: key);

  @override
  _ComPageState createState() => _ComPageState();
}

class _ComPageState extends State<ComPage> with AutomaticKeepAliveClientMixin {
  var loadingDialog;
  BussschBean bussschBean;
  ScrollController _controller = new ScrollController();

  String loadMoreText = "没有更多数据";
  TextStyle loadMoreTextStyle =
      TextStyle(color: const Color(0xFF999999), fontSize: 14.0);

  _ComPageState({Key key}) {
    _controller.addListener(() {
      var maxScroll = _controller.position.maxScrollExtent;
      var pixel = _controller.position.pixels;
      if (maxScroll == pixel && items.length < bussschBean.total) {
        setState(() {
          loadMoreText = "正在加载中...";
          loadMoreTextStyle =
              TextStyle(color: const Color(0xFF4483f6), fontSize: 14.0);
        });
        current++;
        _list(widget.status);
      } else {
        setState(() {
          loadMoreText = "没有更多数据";
          loadMoreTextStyle =
              TextStyle(color: const Color(0xFF999999), fontSize: 14.0);
        });
      }
    });
  }

  var current = 1;
  static int PAGESIZE = 20;
  List<Map<String, dynamic>> maps = List();
  List<RecordsListBean> items = List();

  List<Widget> doWidgets() {
    List<Widget> listTitles = List();
    for (RecordsListBean bean in items) {
      listTitles.add(buildListItem(context, bean));
    }
    return listTitles;
  }

  Widget buildListItem(BuildContext context, RecordsListBean bean) {
    return GestureDetector(
        onTap: () {
          print('inscode:${bean.inscode}');
          String route = '${Routes.comDetail}?inscode=${bean.inscode}';
          Routes.router.navigateTo(context, route,
              replace: false, transition: TransitionType.fadeIn);
        },
        child: Card(
          elevation: 0,
          color: Colors.transparent,
          child: Column(
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          ImageIcon(
                            AssetImage('images/icon_school.png'),
                            color: Color(0xff23AFDC),
                          ),
                          SizedBox(
                            width: 5,
                          ),
                          Text(bean.shortname,
                              style: TextStyle(
                                  color: Color(0xff333333), fontSize: 14))
                        ],
                      ),
                      Row(
                        mainAxisSize: MainAxisSize.max,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          ImageIcon(
                            AssetImage('images/icon_dizhi.png'),
                            color: Color(0xff23AFDC),
                          ),
                          SizedBox(
                            width: 5,
                          ),
                          SizedBox(
                            width: 280,
                            child: Text(bean.address,
                                style: TextStyle(
                                    color: Color(0xff666666), fontSize: 12)),
                          )
                        ],
                      ),
                    ],
                  ),
                  Text(bean.busistatus == '1' ? '营业' : '非营业',
                      style: TextStyle(color: Color(0xff23AFDC), fontSize: 12))
                ],
              ),
            ],
          ),
        ));
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _list(widget.status);
  }

  @override
  void dispose() {
    super.dispose();
    MyDio.getInstance().clearInstance();
  }

  Future<Null> _refresh() async {
    items.clear();
    current = 1;
    await _list(widget.status);
    return;
  }

  _setAppbar() {
//    appBar: _setAppbar(),
    if (widget.organizId == null) {
      return null;
    } else {
      return AppBar(
        backgroundColor: Color(0xff23AFDC),
        elevation: 0,
        title: Text('驾校列表'),
        centerTitle: true,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _setAppbar(),
      body: RefreshIndicator(
        onRefresh: _refresh,
        child: Container(
            color: Colors.white,
            padding: EdgeInsets.fromLTRB(15, 10, 15, 10),
            child: ListView.separated(
              controller: _controller,
              shrinkWrap: true,
              itemBuilder: (context, index) => doWidgets()[index],
              separatorBuilder: (context, index) => Divider(
                color: Color(0xffF0F0F0),
              ),
              itemCount: doWidgets().length,
            )),
      ),
    );
  }

  _list(String status) async {
    Map data = Map<String, dynamic>();
    data["level"] = widget.level == null ? '' : widget.level;
    data["name"] = '';
    data["organizId"] = widget.organizId == null ? '' : widget.organizId;
    data["sonOrganizId"] =
        widget.sonOrganizId == null ? '' : widget.sonOrganizId;
    data["status"] = status;
    data["current"] = current;
    data["pageSize"] = PAGESIZE;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var loginType = await prefs.getString('loginType');
    if (loginType == '2') {
      data['organizId'] = await prefs.getString('loginOrganiz');
    } else if (loginType == '3') {
      data['organizId'] = await prefs.getString('loginOrganiz');
      data['sonOrganizId'] = await prefs.getString('loginSonOrganiz');
    }
    MyDio.getInstance().post('/api/bussSch/list', (data) {
      print(data);
      if (loadingDialog != null) {
        loadingDialog = null;
        Navigator.pop(context);
      }
      bussschBean = BussschBean.fromJson(data);
      setState(() {
        items.addAll(bussschBean.records);
        print('items${items.length},total:${bussschBean.total}');
      });
    }, params: data);
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
